package http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpClientTest {
	public static void main(String[] args) {
		ExecutorService exe = Executors.newFixedThreadPool(100);
		long start = System.currentTimeMillis();
		for (int i = 1; i <= 1000; i++) {
			exe.execute(new Runnable() {
				@Override
				public void run() {
					// 创建HttpClient实例
					HttpClient httpclient = new DefaultHttpClient();
					// 创建Get方法实例
					HttpGet httpgets = new HttpGet("http://172.16.15.110:8080/SWTMS/test.do");
//					HttpGet httpgets = new HttpGet("http://172.16.15.111/SWTMS/test.do");
					try {
						httpclient.execute(httpgets);
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		}
		exe.shutdown();
		while (true) {
			if (exe.isTerminated()) {
				System.out.println(System.currentTimeMillis()-start);
				System.out.println("结束了！");
				break;
			}
		}

	}

	@Test
	public void test01() throws IOException {
		long start = System.currentTimeMillis();
		String url = "http://www.baidu.com";
		CloseableHttpClient httpClient = HttpClients.createDefault();
//		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = null;

		try {
			response = httpClient.execute(httpGet);

			System.out.println("===="+(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK));


			HttpEntity entity = response.getEntity();

			String result = EntityUtils.toString(entity, "UTF-8");

			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(response != null){
				response.close();
			}
			httpClient.close();
		}

		System.out.println("耗时毫秒数："+(System.currentTimeMillis()-start));

	}

}
